import { readFile } from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import Anthropic from '@anthropic-ai/sdk'
import { createLogger } from 'shared/logger'
import { httpAgent } from './httpAgent'
import type { ISearchInput } from '@/shared/types.js'

const logger = createLogger('llm-core')
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const anthropic = new Anthropic({
  httpAgent,
})
/**
 * @reference https://docs.anthropic.com/claude/reference/messages-streaming#streaming-with-sdks
 * @param question
 */
export async function genStreamingCode(question: ISearchInput) {
  logger.info('== llm client(claude3) start ==')
  const systemPrompt = await readFile(path.join(__dirname, './system-prompt.md'), 'utf-8')

  return anthropic.messages.stream({
    model: 'claude-3-opus-20240229',
    max_tokens: 4096,
    system: systemPrompt,
    messages: [
      {
        role: 'user',
        content: composeUserContent(question),
      },
    ],
  })
}

function composeUserContent(question: ISearchInput) {
  const content: Anthropic.MessageParam['content'] = [question.type === 'image_url'
    ? {
        type: 'image' as const,
        source: {
          data: question.value,
          media_type: 'image/png' as const,
          type: 'base64' as const,
        },
      }
    : {
        type: 'text',
        text: question.value + (question.previousCode
          ? `
  Based on the following code, change it to meet my new requirements:
  \`\`\`jsx
  ${question.previousCode}
  \`\`\`
  `
          : ''),
      }]

  return content
}
